import axios from 'axios'
// josn数据序列化
import qs from 'qs'
import { Message } from 'element-ui'
// 线上环境配置axios.defaults.baseURL，生产环境则用proxy代理
// if (process.env.NODE_ENV === 'production') {
//   axios.defaults.baseURL = 'http://localhost:5000'
// } else {
//   axios.defaults.baseURL = 'http://localhost:5000'
// }

axios.defaults.baseURL ='http://localhost:8989'
//axios.defaults.baseURL ='http://192.168.0.138:8989'
axios.defaults.timeout = 5000

axios.defaults.withCredentials = false;
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.interceptors.request.use(
  config => {
    // console.log(window.localStorage.getItem('token'))
    // const token = window.localStorage.getItem('token')
    // token && (config.headers.Authorization = token)
    return config
  },
  err => {
    return Promise.reject(err)
  }
)
axios.interceptors.response.use(
  response => {
    if (response.data.status === 200) {
      return Promise.resolve(response)
    } else {
      if (response.data.code !== 200) {
        Message.warning({
          message: response.data.msg
        })
      }
      return Promise.reject(response)
    }
  },
  error => {
    if (error.response.status) {
      // 服务器状态码不是2开头的的情况
      return Promise.reject(error.response.data)
    }
  }
)

// 返回一个Promise(发送post请求)
export function post (url, params) {
  console.log('param=',JSON.stringify(params))
  return new Promise((resolve, reject) => {
    axios.post(url, JSON.stringify(params))
      .then(res => {
        console.log('res.data=',res.data)
        resolve(res.data)
      })
      
      .catch(err => {
        console.log('err.data=',err.data)
        reject(err.data)
      })
  })
}
// 返回一个Promise(发送get请求)
export function get (url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}

// 重新封装axios方法
export default {
  post, get
}
